﻿using MyWebApp.Common.Exceptions;
using MyWebApp.Common.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MyWebApp.Models;

namespace MyWebApp.Common.UIAttribute
{
    public class CustAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //base.OnAuthorization(filterContext); 
            if (!this.CheckAnonymous(filterContext))
            {
                //未登录验证
                if (AuthUtil.CheckLogin(filterContext.HttpContext) == false)
                {
                    //如果是AJAX请求返回json
                    if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
                    {
                        filterContext.Result = new JsonResult()
                        {
                            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                            Data = new ApiResult { Code = -1, Msg = "未登录或者登录超时" }
                        };
                    }
                    else
                    {
                        //访问页面
                        //string url = filterContext.HttpContext.Request.Path;
                        //"ReturnUrl=" + url
                        //跳转到登录页面
                        FormsAuthentication.RedirectToLoginPage();
                        //filterContext.HttpContext.Response.Redirect();
                        //throw new SessionTimeoutException();
                    }
                }
            }

            base.OnAuthorization(filterContext);

            //鉴权处理
            if (filterContext.HttpContext.Response.StatusCode == 403)
            {
                //跳转到无权限提示页面
                filterContext.Result = new RedirectResult("/Error/Forbidden");
            }
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            if (!httpContext.User.Identity.IsAuthenticated)
                return false;
            bool result = AuthUtil.CheckUserRight(httpContext);
            if (!result)
            {
                httpContext.Response.StatusCode = 403;
            }
            return result;
        }

        /// <summary>
        /// [Anonymous标记]验证是否匿名访问
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        protected bool CheckAnonymous(AuthorizationContext filterContext)
        {
            //验证是否是匿名访问的Action
            object[] attrsAnonymous = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true);
            //是否是Anonymous
            var Anonymous = attrsAnonymous.Length > 0;
            return Anonymous;
        }
    }
}